package com.ctcemti.mdm.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传类（可更新）
* <p>Title: FileUploadUtils</p>  
* <p>Description: </p>  
* @author bxf  
* @date 2019年7月9日
 */
@Slf4j
public class FileUploadUtils {



	/**
	 * 文件上传
	 * <p>Title: springUpload</p>  
	 * <p>Description: </p>  
	 * @author bxf
	 * @date 2019年7月9日 下午4:01:57    
	 * @param request
	 * @param path
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@SuppressWarnings("finally")
	public static boolean springUpload(HttpServletRequest request, String path, String filename, List<Map<String,Object>> list){
		boolean flag = true;
		//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver commonmultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		try{
			File folder = new File(path);
			if (!folder.exists()) {
				boolean mkFlag = folder.mkdirs();
				if (mkFlag) {
					log.error("未找到上传文件夹，新建新建文件夹");
				}
			}
			//检查form中是否有enctype="multipart/form-data"
			if(commonmultipartResolver.isMultipart(request)){
				//将request变成多部分request
				MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
				//获取所有文件名称
				Iterator<String> iter = multiRequest.getFileNames();
				if(iter.hasNext()){
					//获取文件
					MultipartFile file=multiRequest.getFile(iter.next().toString());
					if(file!=null){
						System.out.println(file.getOriginalFilename()+"++++"+file.getName());
						String fileName = file.getOriginalFilename();
						String type = fileName.substring(fileName.lastIndexOf(".")+1);
						Map<String,Object> map = new HashMap<String,Object>();
						file.transferTo(new File(path+"//"+filename+"."+type));
						map.put("newfilename",filename+"."+type);
						list.add(map);
					}
				}
			}
		} catch (IllegalStateException | IOException e) {
			flag = false;
		}finally{
			return flag;
		}

	}
   /* *
    * @Author bxf
    * @Description 下载文件
    * @Date 8:53 2019/9/13
    * @param fileName
    * @param request
    * @param response
    * @param file
    * @return void
    */
	public static void downLoadExcel(String fileName,HttpServletRequest request, HttpServletResponse response,File file) throws IOException {
		FileInputStream fis = null;
		OutputStream out = null;
		try {
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-Type", "application/vnd.ms-excel");
            if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
            }else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌
            }

            response.setHeader("Content-disposition",
                    String.format("attachment; filename=\"%s\"", fileName));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
			fis = new FileInputStream(file);
			byte[] b = new byte[1024];
			int len;
			out = response.getOutputStream();
			while((len=fis.read(b))>0){
				out.write(b,0,len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(fis!=null){
				fis.close();
			}
			if(out!=null){
				out.close();
			}
			file.deleteOnExit();
		}
	}

	public static String uploadFile(MultipartFile file,String uploadfilepath){
		String uuid = UUID.randomUUID().toString().trim();
		String fileN=file.getOriginalFilename();
		String fileName=uuid+fileN.substring(fileN.lastIndexOf("."));
		File fileMkdir=null;
		try {
//			LocalDateTime nowTime = LocalDateTime.now();
//			int year = nowTime.getYear();
//			int mouth = nowTime.getMonthValue();
//			int Day = nowTime.getDayOfMonth();
//			String filePath=uploadfilepath+File.separator+year+File.separator+mouth+File.separator+Day;
			fileMkdir=new File(uploadfilepath);
			if(!fileMkdir.exists()) {
				fileMkdir.mkdirs();
			}
			FileOutputStream os = new FileOutputStream(fileMkdir.getPath()+File.separator+fileName);
			InputStream in = file.getInputStream();
			int b = 0;
            byte[] tempbytes = new byte[1000];
            while((b=in.read(tempbytes))!=-1){ //读取文件
				os.write(tempbytes);
			}
			os.flush(); //关闭流
			in.close();
			os.close();
		} catch (Exception e) {
			return null;
		}
		return "/common/getImage?name="+fileName;
	}

	public static void downWorkbook(HttpServletRequest request,HttpServletResponse response, Workbook workbook,String excelName) throws IOException {
		// 重置响应对象
		response.reset();
		// 当前日期，用于导出文件名称
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = "["+excelName+"-"+sdf.format(new Date())+"]";
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-Type", "application/vnd.ms-excel");
		if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
			dateStr = new String(dateStr.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
		} else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
			dateStr = URLEncoder.encode(dateStr, "UTF-8");// IE浏览器
		}else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
			dateStr = new String(dateStr.getBytes("UTF-8"), "ISO8859-1");// 谷歌
		}

		response.setHeader("Content-disposition",
				String.format("attachment; filename=\"%s\"", dateStr+".xls"));
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		// 写出数据输出流到页面
		OutputStream output = null;
		BufferedOutputStream bufferedOutPut = null;
		try {
			output = response.getOutputStream();
			bufferedOutPut = new BufferedOutputStream(output);
			workbook.write(bufferedOutPut);
			bufferedOutPut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(bufferedOutPut!=null){
				bufferedOutPut.close();
			}
			if(output!=null){
				output.close();
			}
		}
	}
}
